package org.zhxy.core.principal.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.zhxy.common.config.MapperFactory;
import org.zhxy.common.response.Result;
import org.zhxy.common.utils.Constants;
import org.zhxy.entity.personnel.TeacherDepartment;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class DepartmentService {

    public Result saveOrUpdateTeacherDepartment(Map<String, Object> map) {
        String userId = map.get(Constants.Parameters.USER_ID).toString();
        QueryWrapper<TeacherDepartment> teacherDepartmentQueryWrapper = new QueryWrapper<>();
        teacherDepartmentQueryWrapper.eq(Constants.DB.STATUS,Constants.CharacterNumber.ONE);
        teacherDepartmentQueryWrapper.eq(Constants.DB.TEACHER_ID,userId);
        List<TeacherDepartment> teacherDepartments = MapperFactory.teacherDepartmentMapper.selectList(teacherDepartmentQueryWrapper);
        if(!CollectionUtils.isEmpty(teacherDepartments)){
            for (TeacherDepartment teacherDepartment : teacherDepartments) {
                teacherDepartment.setStatus(Constants.CharacterNumber.TWO);
                MapperFactory.teacherDepartmentMapper.updateById(teacherDepartment);
            }
        }

        String departmentIds = map.get(Constants.Parameters.DEPARTMENT_IDS).toString();
        for (String departmentId : departmentIds.split(Constants.Sign.COMMA)) {
            TeacherDepartment teacherDepartment = TeacherDepartment.builder().status(Constants.CharacterNumber.ONE).departmentId(departmentId).teacherId(userId).build();
            MapperFactory.teacherDepartmentMapper.insert(teacherDepartment);
        }

        return Result.SUCCESS();
    }
}
